package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.qianniu.napi.admin.entity.Health;
import com.qianniu.napi.admin.entity.Store;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.IHealthService;
import com.qianniu.napi.admin.service.IStoreService;
import com.qianniu.napi.common.util.ExportExcel;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2020-03-25
 */
@Controller
public class HealthController {

    private static final Logger logger = LoggerFactory.getLogger(HealthController.class);

    @Autowired
    private IHealthService healthService;
    @Autowired
    private IStoreService storeService;

    @RequiresPermissions("admin:health:index")
    @RequestMapping("admin/health/index")
    public String index(Model model) {
        Wrapper<Store> wrapper = new EntityWrapper<Store>()
                .setSqlSelect("id,name")
                .eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid());

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getSid() != null) wrapper.eq("id", user.getSid());

        List<Store> stores = storeService.selectList(wrapper);
        model.addAttribute("stores", stores);

        return "admin/health";
    }

    @RequiresPermissions("admin:health:list")
    @RequestMapping("/admin/health/list")
    @ResponseBody
    public Page<Health> list(
            @RequestParam(value = "storeid", required = false) Long storeid,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "offset", required = false) Integer offset,
            @RequestParam(value = "statday", required = false) String statday,
            @RequestParam(value = "search", required = false) String search,
            @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Health> wrapper = new EntityWrapper<Health>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search).or().like("phone", search)
                    .or().like("sname", search).or().like("cardno", search);

        if (!Strings.isNullOrEmpty(statday)) {
            wrapper.eq("statday", statday);
        }
        if (type != null && type.intValue() > 0) wrapper.eq("type", type);
        if (storeid != null && storeid.intValue() > 0) wrapper.eq("sid", storeid);

        Page<Health> page = healthService.selectPage(new Page<Health>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequiresPermissions("admin:health:add")
    @RequestMapping("/admin/health/add")
    public String add(@Valid Health bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.insert();
        return "admin/health";
    }

    @RequestMapping("/admin/health/getHealthById")
    @ResponseBody
    public Health getHealthById(long id) {
        Health health = healthService.selectById(id);
        return health;
    }

    @RequestMapping("/admin/health/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = healthService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequiresPermissions("admin:health:export")
    @RequestMapping("/admin/health/export")
    @ResponseBody
    public void export(HttpServletResponse response,
                       @RequestParam(value = "storeid", required = false) Long storeid,
                       @RequestParam(value = "type", required = false) Integer type,
                       @RequestParam(value = "statday", required = false) String statday,
                       @RequestParam(value = "search", required = false) String search) {

        Wrapper<Health> wrapper = new EntityWrapper<Health>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search).or().like("phone", search)
                    .or().like("sname", search).or().like("cardno", search);

        if (!Strings.isNullOrEmpty(statday)) {
            wrapper.eq("statday", statday);
        }
        if (type != null && type.intValue() > 0) wrapper.eq("type", type);
        if (storeid != null && storeid.intValue() > 0) wrapper.eq("sid", storeid);

        List<Health> list = healthService.selectList(wrapper);
        if (list == null || list.size() == 0) return;

        Store store = storeService.selectById(storeid);
        String city = store.getCity() == null ? "" : store.getCity().replace("undefined", "");
        String title = city + store.getName() + "出入口体温检测台账(预检分诊记录)";
        List<String> headerList = Lists.newArrayList();
        headerList.add("序号");
        headerList.add("日期");
        headerList.add("姓名");
        headerList.add("性别");
        headerList.add("年龄");
        headerList.add("联系电话");
        headerList.add("现住址");
        headerList.add("身份证号");
        headerList.add("工作单位");
        headerList.add("体温");
        headerList.add("近期外出");
        headerList.add("接触史");
        headerList.add("患者流向");
        ExportExcel excel = new ExportExcel(title, headerList);
        try {

            for (int i = 0; i < list.size(); i++) {
                Row row = excel.addRow();
                excel.addCell(row, 0, i + 1, 2, list.get(i).getName().getClass());
                excel.addCell(row, 1, list.get(i).getStatday(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 2, list.get(i).getName(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 3, list.get(i).getSex() == null ? "" : list.get(i).getSex() == 1 ? "男" : "女", 2, list.get(i).getName().getClass());
                excel.addCell(row, 4, list.get(i).getAge() == null ? "" : list.get(i).getAge(), 2, list.get(i).getName().getClass());

                excel.addCell(row, 5, list.get(i).getPhone(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 6, list.get(i).getAddress(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 7, list.get(i).getCardno(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 8, list.get(i).getCompany(), 2, list.get(i).getName().getClass());
                excel.addCell(row, 9, list.get(i).getTiwen(), 2, list.get(i).getName().getClass());

                excel.addCell(row, 10, list.get(i).getIsleave() == null || list.get(i).getIsleave() == -1 ? "无" : "有", 2, list.get(i).getName().getClass());
                excel.addCell(row, 11, list.get(i).getIsjiechu() == null || list.get(i).getIsleave() == -1 ? "无" : "有", 2, list.get(i).getName().getClass());
                if (store.getType().equals("3938"))
                    excel.addCell(row, 12, list.get(i).getIotype() == null || list.get(i).getIotype() == 1 ? "就诊" : "转诊", 2, list.get(i).getName().getClass());
                else
                    excel.addCell(row, 12, list.get(i).getIotype() == null || list.get(i).getIotype() == 1 ? "流入" : "流出", 2, list.get(i).getName().getClass());
            }

            excel.write(response, title, statday.replaceAll("-", ""));
        } catch (Exception e) {
            logger.error("------------health data export error", e);
        } finally {
            excel.dispose();
        }

    }

}
